<?php

namespace App\Http\Middleware;

use App\Exceptions\LoginException;
use App\Models\Apiuser;
use Closure;

class CheckApi
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $username = $request->header("username");
        $password = $request->header("password");
        $timestemp = $request->header("timestemp");
        $sign = $request->header("sign");
        // echo $sign; 
        $model = Apiuser::where("username", $username)->where("password", $password)->first();
        # 判断他是否查询到数据
        if (!$model) {
            // return response()->json(["status" => 1000, "msg" => "账号或密码不存在"], 401);
            throw new LoginException("账号或密码不存在",1000);
        }
        # 账号密码正确，比对一下sign签名是否一致
        $token = $model->token;
        #后台计算出来的签名
        $signatrue = md5($username . $password . $token . $timestemp);
        # 判断他是否正确,后台的签名和他传入进来的签名是否一致
        if ($sign != $signatrue) {
            throw new LoginException("签名有误",1001);
            // return response()->json(["status" => 1001, "msg" => "签名有误"], 404);
        }
        return $next($request);
    }
}
